package com.rockcent.mall.lib.helper;

import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.ProductEventType;
import com.rockcent.mall.lib.dto.ProductEventDto;
import com.rockcent.mall.lib.repository.CustomerRepository;
import com.rockcent.mall.lib.repository.ProductEventRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by zhangjh on 2016/10/13.
 * 访客的行为记录类
 */
@Component
public class ProductEventHelper {

    private static final Logger log = LoggerFactory.getLogger(ProductEventHelper.class);

    @Autowired
    private ProductEventRepository productEventRepository;
    @Autowired
    private CustomerRepository customerRepository;

    /**
     * 产品事件记录
     * @param orderItem
     * @param useNum 使用数量
     * @param eventType 时间类型
     */
    public void productEventSave(MerchantOrder order, MerchantOrderItem orderItem, Long useNum, ProductEventType eventType){
        if (useNum == null) {
            useNum = 1L;
        }
        ProductEvent productEvent = new ProductEvent();
        if(orderItem.getChannelId() != null){
            productEvent.setChannel(orderItem.getChannelId().toString());
        }

        productEvent.setEventType(eventType);
        productEvent.setSalesCode(orderItem.getSalesCode());
        productEvent.setBuyer(order.getCustomerName());
        productEvent.setBuyerId(order.getCustomerId());
        productEvent.setMallId(order.getMallId());
        productEvent.setMerchantId(order.getMerchantId());
        productEvent.setPrice(orderItem.getSingleAmount());
        productEvent.setProductId(orderItem.getProductId());
        productEvent.setShareFee(orderItem.getShareFee());
        productEvent.setSharer(orderItem.getSharerNickName());
        productEvent.setSharerId(orderItem.getSharerId());
        productEvent.setProductType(order.getOrderType().toString());
        productEvent.setProductName(orderItem.getProductName());
        productEvent.setTotalPrice(orderItem.getDiscountAmount());
        productEvent.setNum(useNum);
        productEvent.setMallOrderNum(orderItem.getMallOrderNum());
        productEventRepository.save(productEvent);
    }

    /**
     * 用户浏览
     *  productList 用户浏览的商品，不能为空
     *  channelId 渠道 可以为空
     *  shareCode 分享码，可以为空
     *  salesCode 分销码 可以为空
     *  customerDto 访客信息，访客ID，nickName
     *
     *  example:
     *  ProductEventDto productEventDto = new ProductEventDto();
     *   productEventDto.setEventType(ProductEventType.VIEWED); ->event类型可以改
     *   productEventDto.setCustomerId(customerDto.getId()); ->当前用户ID
     *   productEventDto.setCustomerName(customerDto.getNickName()); ->当前用户名
     *   productEventHelper.view(pageResult1.data,productEventDto);  -> 产品列表 && 信息
     */
    public void view(List<Product> productList,ProductEventDto productEventDto){
        productList.forEach(product ->{
            productEventDto.setProduct(product);
            productEventRecord(productEventDto);
        });
    }
    /**
     * 保存用户浏览痕迹,
     * 记录规则：只有通过他人的分享进入的才会记录分享人信息，通过分享码（分享码，分享人名、Id），其他的一律记录在buyer、buyer_id中，分享动作不需要记录分享码
     *  product 用户浏览的商品，不能为空
     *  channelId 渠道 可以为空
     *  shareCode 分享码，可以为空
     *  salesCode 分销码 可以为空
     *  customerDto 访客信息，访客ID，nickName
     *  merchantOrderItem 如果下单，订单信息不能为空
     *  eventType 事件类型，不能为空，ARRIVAL("上架"),NOT_ARRIVAL("下架"),VIEWED("浏览"),CLICKED("点击"),ORDERED("下单"),SALED("销售"),VERIFIED("核销"),SHARED("分享"),
     *  Long 返回 ProductEven 记录ID
     */
    public Long productEventRecord(ProductEventDto productEventDto){
        Product product = productEventDto.getProduct();
        String channelId = productEventDto.getChannelId();
        ProductEventType eventType = productEventDto.getEventType();
        String salesCode = productEventDto.getSalesCode();
        String shareCode = productEventDto.getShareCode();
        MerchantOrderItem merchantOrderItem = productEventDto.getMerchantOrderItem();

        if (product==null){
            throw new RuntimeException("product 不能为空");
        }
        ProductEvent productEvent = new ProductEvent();
        //保存渠道
        if (StringUtils.isNotBlank(channelId)) {
            productEvent.setChannel(channelId);
        }
        //保存事件类型
        if (eventType == null){
            throw new RuntimeException("evenType 不能为空");
        }
        productEvent.setEventType(eventType);
        //分销码
        productEvent.setSalesCode(salesCode);
        //保存访客信息
        if (StringUtils.isNotBlank(productEventDto.getCustomerName()) ){
            productEvent.setBuyer(productEventDto.getCustomerName());
        }
        if(productEventDto.getCustomerId() != null){
            productEvent.setBuyerId(productEventDto.getCustomerId());
        }
        //保存产品信息
        productEvent.setMallId(product.getMallId());
        productEvent.setMerchantId(product.getMerchantId());
        productEvent.setPrice(product.getSellPrice());
        //当marketId为null时，表示商品未分销，记录productId，当不为null时，表示分销，记录marketId；
        productEvent.setProductId(product.getId());
        productEvent.setShareFee(product.getShareFee());
        productEvent.setProductType(product.getType().toString());
        productEvent.setProductName(product.getName());
        //如果是分享的,保存分享者信息
        if (StringUtils.isNotBlank(shareCode)){
            //分享码
            Customer sharer = customerRepository.findByShareCode(shareCode);
            if (sharer != null) {
                productEvent.setShareCode(shareCode);
                productEvent.setSharerId(sharer.getId());
                productEvent.setSharer(sharer.getNickName());
            }
        }
        //默认数量为1，则总价为售价
        productEvent.setNum(1L);
        productEvent.setTotalPrice(product.getSellPrice());
        //如果是购买的，订单信息不能为空
        if (ProductEventType.ORDERED ==eventType) {
            if ( merchantOrderItem == null){
                throw new RuntimeException("merchantOrderItem 不能为空");
            }
            productEvent.setNum(merchantOrderItem.getBuyCount());
            productEvent.setTotalPrice(merchantOrderItem.getTotalAmount());
            productEvent.setMallOrderNum(merchantOrderItem.getMallOrderNum());
        }

        return productEventRepository.save(productEvent).getId();
    }


}
